package com.polarrose.wsf.stats;

import java.util.HashMap;
import java.util.Map;

public class StatisticsCollector {

	private final Map<String, CallStatistics> stats = new HashMap<String, CallStatistics>();

	public CallStatistics getCallStatistics(String callName) {
		return getStatisticsForCall(callName);
	}

	public void incrementCounter(String callName, boolean wasSuccess, long executionTime) {
		CallStatistics stat = getStatisticsForCall(callName);
		stat.incrementCounters(wasSuccess, executionTime);
	}

	private CallStatistics getStatisticsForCall(String callName) {
		CallStatistics callStatistics = stats.get(callName);
		if (callStatistics == null) {
			synchronized (stats) {
				callStatistics = stats.get(callName);
				if (callStatistics == null) {
					callStatistics = new CallStatistics(callName);
					stats.put(callName, callStatistics);
				}
			}
		}
		return callStatistics;
	}

	public CallStatistics[] getAllCallStatistics() {
		synchronized (stats) {
			return stats.values().toArray(new CallStatistics[stats.size()]);
		}
	}
}
